package com.gzx.plugin.data.wckj.service.impl;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.gzx.plugin.data.core.utils.MD5Utils;
import com.gzx.plugin.data.core.utils.ServerIpUtil;
import com.gzx.plugin.data.wckj.config.WckjConfig;
import com.gzx.plugin.data.wckj.entity.DataWckjYwyhid;
import com.gzx.plugin.data.wckj.mapper.DataWckjYwyhidMapper;
import com.gzx.plugin.data.wckj.service.ICaseApiService;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@DS("data")
@RequiredArgsConstructor
public class CaseApiServiceImpl implements ICaseApiService {
    //5.1查询业务用户id接口
    @Value("${serverIp.enableIp}")
    private String serverIp;

    private final WckjConfig wckjConfig;

    private final DataWckjYwyhidMapper dataWckjYwyhidMapper;

    @PostConstruct
    public void init() {
        validateConfig();
    }

    private void validateConfig() {
        if (StringUtils.isAnyBlank(wckjConfig.getUrl(), wckjConfig.getOrgCode(), wckjConfig.getOrgPwd(), wckjConfig.getUrgeCase(), wckjConfig.getOrgCode12(), wckjConfig.getOrgPwd12(), serverIp)) {
            throw new IllegalStateException("微财接口配置参数不完整，请检查配置项");
        }
    }

    @Override
    public void urgeCaseM4() {
        processCase(wckjConfig.getOrgCode(), wckjConfig.getOrgPwd(), "M4+");
    }

    @Override
    public void urgeCaseM7() {
        processCase(wckjConfig.getOrgCode(), wckjConfig.getOrgPwd(), "M7+");
    }

    @Override
    public void urgeCaseM12() {
        processCase(wckjConfig.getOrgCode12(), wckjConfig.getOrgPwd12(), "M12+");
    }

    private void processCase(String orgCodeParam, String orgPwdParam, String caseBatch) {
        if (serverIp.equals(ServerIpUtil.getServerIp())) {
            log.info("当前服务器IP：{}为指定运行机器, 开始启动5.1接口查询{}业务用户ID接口......", serverIp, caseBatch);
            String resultJsonData = sentHttpRequest(orgCodeParam, orgPwdParam);
            if (StringUtils.isNotBlank(resultJsonData)) {
                batchSave(resultJsonData, caseBatch);
            }
            log.info("本次查询{}业务用户ID接口结束......", caseBatch);
        }
    }

    private String sentHttpRequest(String orgCode, String orgPwd) {
        try {
            Map<String, Object> paramMap = new HashMap<>();
            // 请求体参数对象 params
            paramMap.put("orgCode", orgCode);
            paramMap.put("orgPwd", orgPwd);
            String secret = MD5Utils.toMD5(orgCode + orgPwd);
            // 创建HTTP请求对象
            HttpRequest post = HttpUtil.createPost(wckjConfig.getUrl() + wckjConfig.getUrgeCase()).timeout(10000);// 设置超时时间为10秒
            // 设定请求头
            post.header(Header.CONTENT_TYPE, "application/json");
            post.header("Secret", secret);
            // 设定请求体
            post.body(JSON.toJSONString(paramMap));
            try (HttpResponse execute = post.execute()) {
                int statusCode = execute.getStatus();
                if (statusCode == 200) {
                    String body = execute.body();
                    log.info("查询业务用户ID接口响应参数:{}", body);
                    return body;
                } else {
                    log.error("调用微财接口出错，状态码：{}", statusCode);
                    return "";
                }
            }
        } catch (Exception e) {
            log.error("调用微财接口出错...", e);
            return "";
        }
    }

    public void batchSave(String resultJsonData, String caseBatch) {
        try {
            JSONObject resultJson = JSON.parseObject(resultJsonData);
            if (!"0".equals(resultJson.getString("status"))) {
                log.error("接口返回状态非成功状态: {}", resultJson.getString("status"));
                return;
            }

            if (!resultJson.containsKey("data")) {
                log.error("响应数据中缺少data字段");
                return;
            }

            JSONObject dataJson = resultJson.getJSONObject("data");
            if (dataJson == null || !dataJson.containsKey("list")) {
                log.error("data字段中缺少list字段");
                return;
            }

            List<String> ywyhidsList = dataJson.getJSONArray("list").toJavaList(String.class);
            if (CollectionUtils.isEmpty(ywyhidsList)) {
                log.info("响应报文中list参数为空");
                return;
            }

            int batchSize = 500;
            List<DataWckjYwyhid> bufferList = new ArrayList<>(batchSize);
            int totalCount = 0;

            for (int i = 0; i < ywyhidsList.size(); i++) {
                DataWckjYwyhid entity = new DataWckjYwyhid();
                entity.setYwyhId(ywyhidsList.get(i));
                entity.setCaseBatch(caseBatch);
                bufferList.add(entity);

                if ((i + 1) % batchSize == 0 || i == ywyhidsList.size() - 1) {
                    dataWckjYwyhidMapper.insertBatch(bufferList);
                    totalCount += bufferList.size();
                    bufferList.clear();

                    // 根据实际需要决定是否保留休眠
                    if ((i + 1) % (batchSize * 5) == 0) {
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            log.info("休眠被中断，不影响主流程");
                        }
                    }
                }
            }
            log.info("批量保存用户id成功，本次共入库条数：{}", totalCount);
        } catch (JSONException e) {
            log.error("JSON解析失败，数据格式异常", e);
        } catch (DataAccessException e) {
            log.error("数据库操作失败，请检查数据或连接", e);
        } catch (Exception e) {
            log.error("批量保存出现未预期异常", e);
        }
    }
}
